package com.aluka.furme.lm.configuration;

import cn.hutool.json.JSONUtil;
import com.aluka.furme.lm.entity.SysUser;
import com.aluka.furme.lm.service.SysUserService;
import com.aluka.nirvana.framework.core.context.ServletContextAware;
import com.aluka.nirvana.framework.security.principal.BaseUserDetails;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.servlet.http.HttpServletRequest;

/**
 * @author gongli
 * @since 2020-8-10 21:05
 */
@Configuration
public class LoginConfiguration implements AuthenticationProvider {

    @Autowired
    private SysUserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        HttpServletRequest request = ServletContextAware.getRequest();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");
        if(StringUtils.isBlank(username)){
            throw new BadCredentialsException("用户名不能为空");
        }
        if(StringUtils.isBlank(password)){
            throw new BadCredentialsException("密码不能为空");
        }
        SysUser sysUser = userService.getItem(username);
        if(sysUser == null || !passwordEncoder.matches(password, sysUser.getPassword())){
            throw new BadCredentialsException("用户名或密码错误!");
        }
        BaseUserDetails userDetails = new BaseUserDetails();
        userDetails.setAdmin(sysUser.isAdmin());
        userDetails.setUsername(username);
        userDetails.setPassword(password);
        userDetails.setUserId(sysUser.getId());
        userDetails.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("TEMP"));
        userDetails.setCustomFields(JSONUtil.parseObj(sysUser));
        return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

}
